package user_service

import "repairs/models"

type User struct {
	ID       int
	Username string
	Password string
	Phone    string
	Email    string
	Name     string
	Class    string
}

// Check 检查用户密码 成功返回用户id, 失败返回0
// 如果用户名不存在会创建
func Check(username, password string) (int, error) {
	exist, err := models.ExistUserByUsername(username)
	if err != nil {
		return 0, err
	}
	if exist {
		return models.CheckLogin(username, password)
	}
	var user = map[string]interface{}{
		"username": username,
		"password": password,
	}
	return models.AddUser(user)
}
func (u *User) GetUser() error {
	user, err := models.GetUserByID(u.ID)
	if err != nil {
		return err
	}
	u.Username = user.Username
	u.Class = user.Class
	u.Phone = user.Phone
	u.Email = user.Email
	u.Name = user.Name
	return nil
}

func (u *User) UpdateLogin() error {
	return models.UpdateLogin(u.ID)
}

//
//func (u *User) Add() error {
//	maps := map[string]interface{}{
//		"username": u.Username,
//		"password": u.Password,
//		"Phone":    u.Phone,
//		"Email":    u.Email,
//		"Name":     u.Name,
//		"Class":    u.Class,
//	}
//	err := models.AddUser(maps)
//	return err
//}

func (u *User) EditUser() error {
	return models.EditUser(u.ID, u.getMaps())
}

func (u *User) getMaps() map[string]interface{} {
	maps := make(map[string]interface{})
	maps["deleted_on"] = 0
	if u.Name != "" {
		maps["name"] = u.Name
	}
	if u.Email != "" {
		maps["email"] = u.Email
	}
	if u.Phone != "" {
		maps["phone"] = u.Phone
	}
	if u.Class != "" {
		maps["class"] = u.Class
	}
	if u.Username != "" {
		maps["username"] = u.Username
	}
	if u.Password != "" {
		maps["password"] = u.Password
	}
	return maps
}
